package com.roc.template.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
@Slf4j
public class LoggerInterceptor {

    @Around("execution(* com.roc.template..*.*Controller.*(..))")
    public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        ObjectMapper obj = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringBuffer method = new StringBuffer();
        method.append(joinPoint.getTarget().getClass().getSimpleName()).append(".");
        method.append(joinPoint.getSignature().getName()).append("#");
        StringBuffer buffer = new StringBuffer();
        buffer.append(method);
        Object[] arguments = joinPoint.getArgs();
        for (Object arg : arguments) {
            if(!(arg instanceof HttpServletRequest || arg instanceof HttpServletResponse || arg instanceof MultipartFile || arg instanceof MultipartFile[])){
                buffer.append(obj.writeValueAsString(arg));
            }
        }

        log.info("request#{}", buffer.toString());
        Object result = joinPoint.proceed();
        log.info("response#{}", method+" "+getResultMessage(obj, result));

        return result;
    }

    private String getResultMessage(ObjectMapper obj, Object result) {
//        String resultStr = null;
        try {
            return obj.writeValueAsString(result);
        } catch (Exception e1) {
            return "";
        }
    }
}
